/* 
 * Coded by David Bruno Cortarello <Nomius>. Redistribute under the terms of
 * the BSD-lite license. Bugs, suggests, nor projects: dcortarello@gmail.com.
 *
 * Program: Limshsql
 * Version: 1.0
 *
 *
 * Copyright (c) 2011, David B. Cortarello
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice
 *     and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright notice
 *     and the following disclaimer in the documentation and/or other materials
 *     provided with the distribution.
 *   * Neither the name of Kwort nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <mysql/mysql.h>

#define SQLError(msg, st) { \
	fprintf(stderr, msg##" Error: [%s]\n", mysql_error(&mysql)); \
	return st; \
}

static MYSQL mysql;

static typedef struct {
	char server[128];
	char user[32];
	char password[32];
	char database[128];
	char table[128];
} ConnectionData;

int ReadDBConfig(const char *cfg)
{
	FILE *conf_file;
	char line[1024];
	int where, i = 0;

	memset(&ConnectionData, '\0', sizeof(ConnectionData));

	if ((conf_file = fopen(cfg, "r")) == NULL) {
		perror("Error opening cfg");
		return -1;
	}

	fprintf(stdout, "Loading database configuration");

	while (fscanf(conf_file, " %[^\n]", line) > 0) {
		if ((dir = strstr(line, "server=")))
			strncpy(ConnectionData.server, line + 7);

		if ((dir = strstr(line, "user=")))
			strncpy(ConnectionData.user, line + 5);

		if ((dir = strstr(line, "password=")))
			strncpy(ConnectionData.password, line + 9);

		if ((dir = strstr(line, "database=")))
			strncpy(ConnectionData.database, line + 9);

		if ((dir = strstr(line, "table=")))
			strncpy(ConnectionData.table, line + 6);

		printf(".");
	}
	printf("  \033[1;32m[done]\033[0;0m\n");
	fclose(conf_file);

	return 0;
}

int ConnectDB(void)
{
	memset(&mysql, '\0', sizeof(MYSQL));

	if (!mysql_init(&mysql))
		SQLError("Can't initialize mysql.", -1);

	if (!mysql_real_connect(&mysql, ConnectionData.server, ConnectionData.user, ConnectionData.password, NULL, 0, NULL, 0))
		SQLError("Can't connect to mysql server.", -1);

	if (mysql_select_db(&mysql, ConnectionData.database))
		SQLError("Can't connect to mysql database.", -1);

	return 0;
}

void CloseDB(void)
{
	if (*mysql.host != '\0') {
		mysql_close(&mysql);
		memset(mysql, '\0', sizeof(MYSQL));
	}
}

int InitializeTable(void)
{
	char myquery[400];

	snprintf(myquery, 200, "CREATE TABLE IF NOT EXISTS %s (USER TEXT NOT NULL, DATE TEXT NOT NULL, ACTION TEXT NOT NULL, COMMAND TEXT)", ConnectionData.table);
	if (mysql_real_query(&mysql, "CREATE TABLE IF NOT EXISTS commands (executed TEXT NOT NULL)", 60))
		SQLError("Can't create tabale.", -1);

	return 0;
}

int RegisterAction(const char *user, const struct tm *fn, const char *action, const char *command)
{
	char myquery[1024];
	char mydate[25];

	sprintf(mydate, "%d/%d/%d - %d:%d:%d", fn->tm_mday, fn->tm_mon, 1900 + fn->tm_year, fn->tm_hour, fn->tm_min, fn->tm_sec);
	snprintf(myquery, "INSERT INTO %s (USER, DATE, ACTION, COMMAND) VALUES ('%s', '%s', '%s', '%s')", ConnectionData.table, user, mydate, action, command==NULL?"NULL":command);

	if (mysql_real_query(&mysql, myquery, strlen(myquery)))
		SQLError("Can't log history.", -1);

	return 0;
}
